package postlogic

import (
	"context"

	"go-zero-admin/apps/system/cmd/rpc/internal/svc"
	"go-zero-admin/apps/system/cmd/rpc/syspb"
	"go-zero-admin/apps/system/model"
	"go-zero-admin/pkg/tool"
	"go-zero-admin/pkg/xerr"

	"github.com/jinzhu/copier"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type AddPostLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
	isExPostNameCodeLogic *IsExPostNameCodeLogic
}

func NewAddPostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddPostLogic {
	return &AddPostLogic{
		ctx:                   ctx,
		svcCtx:                svcCtx,
		Logger:                logx.WithContext(ctx),
		isExPostNameCodeLogic: NewIsExPostNameCodeLogic(ctx, svcCtx),
	}
}

func (l *AddPostLogic) AddPost(in *syspb.AddPostReq) (*syspb.AddPostResp, error) {
	post := in.GetParams()
	if post == nil || post.GetPostName() == "" || post.GetPostCode() == "" ||
		post.GetCreateUser() == "" || post.GetUpdateUser() == "" {
		return nil, errors.Wrapf(xerr.NewErrMsg("新增岗位失败：参数缺失"),
			tool.GetErrMsgFormat("insert post"), "params is not existed", in)
	}

	// 校验参数重复
	isExistResp, err := l.isExPostNameCodeLogic.IsExPostNameCode(&syspb.IsExPostNameCodeReq{
		Name: post.GetPostName(),
		Code: post.GetPostCode(),
	})
	if err != nil {
		return nil, err
	}
	if isExistResp.GetIsExist() {
		return nil, errors.Wrapf(xerr.NewErrMsg("新增岗位："+post.GetPostName()+" 失败，名称或编码已经存在"),
			tool.GetErrMsgFormat("insert post"), "post name or code is existed", post)
	}

	// 数据转换
	var data model.SysPost
	_ = copier.Copy(&data, post)

	// 保存数据
	_, err = l.svcCtx.SysPostModel.InsertEx(l.ctx, nil, []*model.SysPost{&data})
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DbError),
			tool.GetErrMsgFormat("insert post"), err, in)
	}

	return &syspb.AddPostResp{}, nil
}
